/**
 * 主功能页面，用于设置行业 author:zhushiyou date:2016年10月19日20:18:42
 */
var attachmentList = {
    /**
     * 调用ajax取得标签和知识 pageNum当前请求页码 pageSize请求个数
     */
    loadData: function () {//
        var data = common.strToJson(window.localStorage.currentUserAttachDownloadFiles);
        //测试数据
       /* data = [
            {
                "att_day": "25",
                "att_month": "11",
                "att_year": "2016",
                "filename": "c9eddec4-77e8-4860-86cd-558264e3e63b,客户认可信和DVR索引.xlsx",
                "filesize": "54.59KB",
                "fileurl": "http://121.196.222.96:8096/shellkm/file/appdownloadFile/c9eddec4-77e8-4860-86cd-558264e3e63b",
                "fname": "客户认可信和DVR索引",
                "pk_attachment": "c9eddec4-77e8-4860-86cd-558264e3e63b",
                "pk_business": "",
                "upload_type": "xlsx"
            },
            {
                "att_day": "25",
                "att_month": "11",
                "att_year": "2016",
                "filename": "198383e0-2fdd-4ad6-8ab3-2f690eb32521,LNG行业.xlsx",
                "filesize": "12.63KB",
                "fileurl": "http://121.196.222.96:8096/shellkm/file/appdownloadFile/198383e0-2fdd-4ad6-8ab3-2f690eb32521",
                "fname": "LNG行业",
                "pk_attachment": "198383e0-2fdd-4ad6-8ab3-2f690eb32521",
                "pk_business": "",
                "upload_type": "xlsx"
            },
            {
                "att_day": "25",
                "att_month": "11",
                "att_year": "2016",
                "filename": "7fa9dfc7-dc5b-4753-a5f7-1e0a18f7f5e6,地铁施工-海瑞克盾构机-中交隧道工程局有限公司-得力士S2M-可耐压S2G-佳度S2V.pdf",
                "filesize": "288.53KB",
                "fileurl": "http://121.196.222.96:8096/shellkm/file/appdownloadFile/7fa9dfc7-dc5b-4753-a5f7-1e0a18f7f5e6",
                "fname": "地铁施工-海瑞克盾构机-中交隧道工程局有限公司-得力士S2M-可耐压S2G-佳度S2V",
                "pk_attachment": "7fa9dfc7-dc5b-4753-a5f7-1e0a18f7f5e6",
                "pk_business": "",
                "upload_type": "pdf"
            },
            {
                "att_day": "25",
                "att_month": "11",
                "att_year": "2016",
                "filename": "47b0fa8f-3be0-4676-8311-f3e0c1363c61,地铁施工-海瑞克盾构机-北京长城贝尔芬格伯格建筑工程有限公司-得力士S2M-可耐压S2G-佳度S2V.pdf",
                "filesize": "558.63KB",
                "fileurl": "http://121.196.222.96:8096/shellkm/file/appdownloadFile/47b0fa8f-3be0-4676-8311-f3e0c1363c61",
                "fname": "城铁施工-海瑞克盾构机-北京长城贝尔芬格伯格建筑工程有限公司-得力士S2M-可耐压S2G-佳度S2V",
                "pk_attachment": "47b0fa8f-3be0-4676-8311-f3e0c1363c61",
                "pk_business": "",
                "upload_type": "pdf"
            }
            ,
            {
                "att_day": "25",
                "att_month": "11",
                "att_year": "2016",
                "filename": "47b0fa8f-3be0-4676-8311-f3e0c1363c61,地铁施工-海瑞克盾构机-北京长城贝尔芬格伯格建筑工程有限公司-得力士S2M-可耐压S2G-佳度S2V.pdf",
                "filesize": "558.63KB",
                "fileurl": "http://121.196.222.96:8096/shellkm/file/appdownloadFile/47b0fa8f-3be0-4676-8311-f3e0c1363c61",
                "fname": "ttt",
                "pk_attachment": "47b0fa8f-3be0-4676-8311-f3e0c1363c61",
                "pk_business": "",
                "upload_type": "pdf"
            }
            ,
            {
                "att_day": "25",
                "att_month": "11",
                "att_year": "2016",
                "filename": "47b0fa8f-3be0-4676-8311-f3e0c1363c61,地铁施工-海瑞克盾构机-北京长城贝尔芬格伯格建筑工程有限公司-得力士S2M-可耐压S2G-佳度S2V.pdf",
                "filesize": "558.63KB",
                "fileurl": "http://121.196.222.96:8096/shellkm/file/appdownloadFile/47b0fa8f-3be0-4676-8311-f3e0c1363c61",
                "fname": "北京长城贝尔芬格伯格建筑工程有限公司-得力士S2M-可耐压S2G-佳度S2V",
                "pk_attachment": "47b0fa8f-3be0-4676-8311-f3e0c1363c61",
                "pk_business": "",
                "upload_type": "pdf"
            }
            ,
            {
                "att_day": "25",
                "att_month": "11",
                "att_year": "2016",
                "filename": "47b0fa8f-3be0-4676-8311-f3e0c1363c61,地铁施工-海瑞克盾构机-北京长城贝尔芬格伯格建筑工程有限公司-得力士S2M-可耐压S2G-佳度S2V.pdf",
                "filesize": "558.63KB",
                "fileurl": "http://121.196.222.96:8096/shellkm/file/appdownloadFile/47b0fa8f-3be0-4676-8311-f3e0c1363c61",
                "fname": "我是谁",
                "pk_attachment": "47b0fa8f-3be0-4676-8311-f3e0c1363c61",
                "pk_business": "",
                "upload_type": "pdf"
            }

        ];*/
        if (data == undefined || data.length == 0) {
            $("#attenchmentListDiv").height($(window).height() - $(".header").height());
            common.show_nodata("没有附件信息", "attenchmentListDiv");
        } else {
            data = data.sort(common.rank("fname"));
            //
            for (var i = 0; i < data.length; i++) {
                var att = data[i];
                var publishtime = att.att_year + "." + att.att_month + "." + att.att_day;
                var fileType = att.upload_type;
                //var ohtml = '<div class="line-wrapper"><div class="line-scroll-wrapper">'
                //	       +'<div class="line-normal-wrapper"><div class="detailPpt" dataurl="' + att.fileurl + '" fileName= "' + att.fname + '" filePath= "' + att.pk_attachment +'">';
                var imageurl = "images/";
                switch (fileType.toLowerCase()) {
                    case "docx":
                    case "doc":
                        imageurl += "word";
                        break;
                    case "pdf":
                        imageurl += "pdf";
                        break;
                    case "xlsx":
                    case "xls":
                        imageurl += "excel";
                        break;
                    case "pptx":
                    case "ppt":
                        imageurl += "ppt";
                        break;
                    case "mp4":
                        imageurl += "mp4";
                        break;
                    default:
                        imageurl += "other";
                        break;
                }
                imageurl += ".png";
                var ohtml = '<div class="line-wrapper" id="attachmentList_' + att.pk_attachment + '">'
                    + '  <div class="line-scroll-wrapper">'
                    + '    <div class="line-normal-wrapper" dataurl="' + att.fileurl + '" fileName= "' + att.fname + '" filePath= "' + att.pk_attachment + '" fileTypeStr="' + fileType + '">'
                    + '      <div class="line-normal-left-wrapper">'
                    + '        <div class="line-normal-avatar-wrapper1"><img src="' + imageurl + '"/></div>'
                    + '        <div class="line-normal-info-wrapper">'
                    + '          <div class="line-normal-user-name">' + att.fname + '</div>'
                    + '          <div class="line-normal-msg">' + att.filesize + '</div>'
                    + '          <div class="line-normal-time">' + publishtime + '</div>'
                    + '        </div>'
                    + '      </div>'
                    + '    </div>'
                    + '    <div class="line-btn-delete" dataurl="' + att.fileurl + '" fileName= "' + att.fname + '" delPK= "' + att.pk_attachment + '" fileTypeStr="' + fileType + '" ><div>删除</div></div>'
                    + '  </div>'
                    + '</div>';
                $("#attenchmentListDiv").append(ohtml);
            }

            console.log($("#attenchmentListDiv").html());
            //初始化上拉加载下拉刷新控件
            common.initIscrollBody("attenchDetailListContent");
            //下载事件
            attachmentList.initDownload();
            //
            common.hideLoading();
        }
    },
    //初始化 下载组件
    initDownload: function () {

        $(".line-normal-wrapper").unbind().on("click", function () {
            var url = $(this).attr("dataurl");
            var type = $(this).attr("fileTypeStr"); //url.split(".").pop()
            var fileName = $(this).attr("fileName") + "." + type;
            var id = $(this).attr("filePath");
            var filePath = "shellkm" + "/";
            fileName = id + "," + fileName;
            $("#" + id).addClass(id);

            //判断文件是否已经存在。
            var flag = $file.exists({
                path: filePath,
                file: fileName
            });

            if (flag != "false") {
                attachmentList.openfile(type, filePath, fileName);
                return false;
            }

            url = common.contextPath() + "/file/appdownloadFile/" + id;
            attachmentList.downloadDocx(url, filePath, fileName);
        });

        /**
         * 删除事件的处理
         */
        $(".line-btn-delete").unbind().on("click", function () {
            event.preventDefault();
            var fileName = $(this).attr("fileName");
            var rowPK = $(this).attr("delPK");
            var filePath = "shellkm" + "/";

            var url = $(this).attr("dataurl");
            var type = $(this).attr("fileTypeStr");
            var fileName = $(this).attr("fileName") + "." + type;

            var filePath = "shellkm" + "/";
            fileName = rowPK + "," + fileName;

            common.showConfirm("您确定删除此附件？", function () {
                window.sessionStorage.rowPK = rowPK;
                //删除事件
                $file.remove({
                    path: filePath,
                    file: fileName,
                    callback: "attachmentList.removeCallback()"
                });
            });
        });
    },
    /**
     * 绑定点击事件
     *
     */
    bindEvent: function () {
        $(".closed-head-icon").unbind().on("click", function () {
            summer.closeWin();
        });

        // 点击返回
        $("#attachmentListReturn").unbind().on("click", function () {
            //返回
            window.location.href = "#home";
        });

        $(window).unbind().on('orientationchange', function (e) {
            setTimeout(function () {
                //定义页面列表高度
                $("#collect_List").css("min-height", $(window).height() - $("#header").height());
                // 设定每一行的宽度=屏幕宽度+按钮宽度
                $(".line-scroll-wrapper").width($(".line-wrapper").width() + $(".line-btn-delete").width());
                // 设定常规信息区域宽度=屏幕宽度
                $(".line-normal-wrapper").width($(".line-wrapper").width());
                console.log("line-normal-wrapper====" + $(".line-normal-wrapper").width());
                // 设定文字部分宽度（为了实现文字过长时在末尾显示...）
                $(".line-normal-msg").css("width", "50%");
            }, 200);
        });
    },
    /**
     * 进行页面路由监听配置，覆盖首页设置的路由
     *
     */
    bindRout: function () {
        //首页
        Path.map("#home").to(function () {
            //记录状态
            common.loadPageDiv("html/index.html", false, true);
        });

        //选择详情页面
        Path.map("#detail").to(function () {
            //记录状态
            common.loadPageDiv("html/detail.html", true);
            //session中记录一下
            window.sessionStorage.detailPageFromRout = "collectList";
            window.history.replaceState({}, "title", "index.html")
        });
        Path.listen();
    },
    /**
     * 删除相应的文件
     */
    removeCallback:function (args) {
        if (args.delStatus == 1) {
            common.showTip("文件删除成功");
            var name = "";
            var rowPK = "";
            //临时的解决办法，用于解决删除的操作
            rowPK = window.sessionStorage.rowPK;
            /*if(args.file == undefined){
             rowPK = window.sessionStorage.rowPK;
             }else{
             name = args.file;
             rowPK = name.split(",")[0];
             }*/
            //页面隐藏
            $("#attachmentList_" + rowPK).remove();

            //取得当前的json串值
            var currentUserAttachDownloadFiles = common.strToJson(window.localStorage.currentUserAttachDownloadFiles);
            if (typeof(currentUserAttachDownloadFiles) == "undefined") {
                currentUserAttachDownloadFiles = [];
            }
            //从0开始
            var i = 0;
            //按照PK查找
            for (i = 0; i < currentUserAttachDownloadFiles.length; i++) {
                if (rowPK == currentUserAttachDownloadFiles[i].pk_attachment) {
                    //页面移除
                    currentUserAttachDownloadFiles.splice(i, 1);
                    break;
                }
            }
            ;
            //保存到本地
            window.localStorage.currentUserAttachDownloadFiles = JSON.stringify(currentUserAttachDownloadFiles);
            var data = common.strToJson(window.localStorage.currentUserAttachDownloadFiles);
            if (data == undefined || data.length == 0) {
                $("#attenchmentListDiv").height($(window).height() - $(".header").height());
                common.show_nodata("没有附件信息", "attenchmentListDiv");
            }
        } else {
            common.showTip(args.msg);
        }
    },
    /**
     * 删除部分样式的定义
     */
    attachListDelSize: function () {
        //定义页面列表高度
        $("#collect_List").css("min-height", $(window).height() - $("#header").height());
        // 设定每一行的宽度=屏幕宽度+按钮宽度
        $(".line-scroll-wrapper").width($(".line-wrapper").width() + $(".line-btn-delete").width());
        // 设定常规信息区域宽度=屏幕宽度
        $(".line-normal-wrapper").width($(".line-wrapper").width());
        // 设定文字部分宽度（为了实现文字过长时在末尾显示...）
        $(".line-normal-msg").css("width", "50%");

        // 获取所有行，对每一行设置监听
        var lines = $(".line-normal-wrapper");
        var len = lines.length;
        var lastX, lastXForMobile;

        // 用于记录被按下的对象
        var pressedObj;  // 当前左滑的对象
        var lastLeftObj; // 上一个左滑的对象

        // 用于记录按下的点
        var start;

        // 网页在移动端运行时的监听
        for (var i = 0; i < len; ++i) {
            lines[i].addEventListener('touchstart', function (e) {
                lastXForMobile = e.changedTouches[0].pageX;
                pressedObj = this; // 记录被按下的对象

                // 记录开始按下时的点
                var touches = event.touches[0];
                start = {
                    x: touches.pageX, // 横坐标
                    y: touches.pageY  // 纵坐标
                };
            });

            lines[i].addEventListener('touchmove', function (e) {
                // 计算划动过程中x和y的变化量
                var touches = event.touches[0];
                delta = {
                    x: touches.pageX - start.x,
                    y: touches.pageY - start.y
                };

                // 横向位移大于纵向位移，阻止纵向滚动
                if (Math.abs(delta.x) > Math.abs(delta.y)) {
                    event.preventDefault();
                }
            });

            lines[i].addEventListener('touchend', function (e) {
                if (lastLeftObj && pressedObj != lastLeftObj) { // 点击除当前左滑对象之外的任意其他位置
                    $(lastLeftObj).animate({marginLeft: "0"}, 500); // 右滑
                    lastLeftObj = null; // 清空上一个左滑的对象
                }
                var diffX = e.changedTouches[0].pageX - lastXForMobile;
                if (diffX < -30) {
                    $(pressedObj).animate({marginLeft: "-80px"}, 500); // 左滑
                    lastLeftObj && lastLeftObj != pressedObj &&
                    $(lastLeftObj).animate({marginLeft: "0"}, 500); // 已经左滑状态的按钮右滑
                    lastLeftObj = pressedObj; // 记录上一个左滑的对象
                } else if (diffX > 30) {
                    if (pressedObj == lastLeftObj) {
                        $(pressedObj).animate({marginLeft: "0"}, 500); // 右滑
                        lastLeftObj = null; // 清空上一个左滑的对象
                    }
                }
            });
        }
        //初始化上拉加载下拉刷新控件
        common.initIscrollBody("attenchDetailListContent");
    },
    downloadCall: function (args) {
        var name = args.filename;
        var id = name.split(",")[0];
        $("#" + id).show();
        if (args.isfinish) {
            common.showTip("下载完成");
            $('.' + id).css('width', "70%");
            var path = args.filepath;
            type = name.split(".").pop();
            $("#" + id).removeClass(id);
            setTimeout(function () {
                $("#" + id).hide();
            }, 2000);
            //xiaz
            attachmentList.recordCurrentUserAttachDownloadFiles(name, args.savePath, id, type, args.url, "");
            //最后打开文件
            $file.open({
                "filename": name,//文件全路径
                "filetype": type,
                "filepath": path
            });
        } else {
            var percent = parseInt(args.percent) * 0.75;
            console.log(args.percent + ",percent===" + percent);
            $('.' + id).css('width', percent + "%");
        }
    },
    errorFunction: function (res) {
        alert(res);
    },

    openfile: function (filetype, filepath, filename) {
        $file.open({
            "filename": filename,//文件全路径
            "filetype": filetype,
            "filepath": filepath
        })
    },
    downloadDocx: function (url, filepath, filename) {
        //开始了
        var getNetworkInfo = JSON.parse($net.getNetworkInfo());
        // //判断是否为wifi连接，
        if (getNetworkInfo.Type == "Wifi" || getNetworkInfo.Type == "WiFi") {
            $file.download({
                "url": url,
                "locate": filepath,
                "filename": filename,
                "override": "true",
                "callback": "attachmentList.downloadCall()",
                "error": "attachmentList.errorFunction()"
            });
        } else {
            common.showConfirm("您未链接Wi-Fi，确定使用流量下载附件吗？", function () {
                $file.download({
                    "url": url,
                    "locate": filepath,
                    "filename": filename,
                    "override": "true",
                    "callback": "attachmentList.downloadCall()",
                    "error": "attachmentList.errorFunction()"
                });
            });

        }
    },
    //记录附件下载的公共函数
    recordCurrentUserAttachDownloadFiles: function (fileName, savePath, id, type, url, thisFileSize) {
        //当前年月日计算
        var myDate = new Date();
        //年
        var att_year = myDate.getFullYear();
        //获取当前月份
        var att_month = parseInt(myDate.getMonth()) + 1;
        //获取当前日
        var att_day = myDate.getDate();

        //文件大小
        var fileSize = 0;
        if (thisFileSize == "" || thisFileSize == undefined) {
            //下载的文件信息
            var savePathInfo = $file.getFileInfo(savePath);
            if (typeof(savePathInfo) == "string") {
                fileSize = common.strToJson(savePathInfo).size;
            } else {
                fileSize = savePathInfo.size;
            }
            fileSize = common.calcFileSize(fileSize);
        } else {
            fileSize = thisFileSize;
        }
        //保存当前信息到本地存储当中去
        var thisFileInfo = {
            "att_day": parseInt(att_day) < 10 ? "0" + att_day : att_day,
            "att_month": parseInt(att_month) < 10 ? "0" + att_month : att_month,
            "att_year": att_year,
            "filename": fileName,
            "filesize": fileSize,
            "fileurl": url,
            "fname": fileName.split(",")[1].substring(0, fileName.split(",")[1].lastIndexOf(".")),
            "pk_attachment": id,
            "pk_business": "",
            "upload_type": type
        };
        //取得当前的json串值
        var currentUserAttachDownloadFiles = common.strToJson(window.localStorage.currentUserAttachDownloadFiles);
        if (typeof(currentUserAttachDownloadFiles) == "undefined") {
            currentUserAttachDownloadFiles = [];
        }
        //从0开始
        var i = 0;
        for (i = 0; i < currentUserAttachDownloadFiles.length; i++) {
            console.log(currentUserAttachDownloadFiles[i].fname);
            if (thisFileInfo.pk_attachment == currentUserAttachDownloadFiles[i].pk_attachment) {
                console.log("已经存在");
                break;
            }
        }
        if (i == currentUserAttachDownloadFiles.length) {
            currentUserAttachDownloadFiles.push(thisFileInfo);
            //保存到本地
            window.localStorage.currentUserAttachDownloadFiles = JSON.stringify(currentUserAttachDownloadFiles);
        }
    },
    /**
     * each page
     */
    initialize: function () {
        attachmentList.bindEvent();// 绑定事件
        attachmentList.bindRout();// 绑定路由
        attachmentList.loadData("");// 加载知识
        window.sessionStorage.collect_status = 1;
        //初始化窗口事件
        attachmentList.attachListDelSize();
    }
};
	
	